<template>
  <Modal
    width="1000"
    :value.sync="dialogPriceSetVisible"
    :loading="actionLoading"
    @on-cancel="handleCancle"
    title="价格组设置"
  >
    <Form
      v-show="isBatchSetting"
      ref="formInline"
      :model="formInline"
      :label-width="100"
      inline
    >
      <FormItem label="批量设置组">
        <Select v-model="formInline.select" transfer>
          <Option
            v-for="(item, ki) in priceGroupList"
            :value="item.groupNum"
            :key="ki + item.groupNum"
          >
            {{ item.groupName }}
          </Option>
        </Select>
      </FormItem>
      <FormItem :label-width="0">
        <Button type="primary" @click="handleBatchSetting">确定</Button>
      </FormItem>
    </Form>
    <div class="heigher_table_wrap">
      <Button
        type="primary"
        :disabled="provinceSetList.length === 0"
        @click="handleToGroupByProvince"
        >各省成组</Button
      >
    </div>
    <Tabs v-model="radioValue" @on-click="priceGroupRadioAction">
      <TabPane label="按省设置" name="name2">
        <Table
          :columns="provinceColumns"
          :data="provinceSetList"
          :loading="tableLoading"
        >
          <template slot-scope="{ row, index }" slot="groupNum">
            <Input
              v-model="row.groupNum"
              @on-change="
                handleInputPriceGroup({ type: 'province', row, index })
              "
              placeholder="请输入..."
            />
          </template>
          <template slot-scope="{ row, index }" slot="mainCity">
            <RadioGroup
              v-model="row.mainCity"
              @on-change="handleChangeIsMainCity({ event: $event, row, index })"
            >
              <Radio label="1" :disabled="row.canSetMain == 2">是</Radio>
              <Radio label="2" :disabled="row.canSetMain == 2">否</Radio>
            </RadioGroup>
          </template>
        </Table>
      </TabPane>
    </Tabs>
    <Row slot="footer" style="justify-content: center">
      <Button type="default" @click="handleCancle">取消</Button>
      <Button type="primary" @click="submitAction" :loading="submitLoading"
        >确定</Button
      >
    </Row>
  </Modal>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { generateUuid } from '@/utils/bizUtils';
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    parentGetTemplateFn: {
      type: Function
    },
    productUuid: {
      type: Array,
      default () {
        return [];
      }
    },
    isBatchSetting: {
      type: Boolean
    },
    apiRequestUrl: {
      type: String,
      default: '/sysback/salepricesku/initAreaList?authCreateGroupNum=1'
    },
    submitUrl: {
      type: String,
      default: '/sysback/salepricesku/createGroupAndAreaRel'
    }
  },
  data () {
    return {
      dialogPriceSetVisible: this.visible,
      provinceSetList: [],
      radioValue: 'name2',
      actionLoading: false,
      tableLoading: false,
      submitLoading: false,
      priceGroupList: [],
      // 批量设置
      formInline: {
        select: ''
      },
      initParams: {},
      provinceColumns: [
        {
          title: '设置组',
          slot: 'groupNum',
          align: 'center',
          minWidth: 150
        },
        {
          title: '组名',
          key: 'groupName',
          minWidth: 150
        },
        {
          title: '省',
          key: 'provinceName',
          minWidth: 150
        },
        {
          title: '主城市',
          key: 'cityName',
          minWidth: 150
        },
        {
          title: '业务区域',
          key: 'areaName',
          minWidth: 150
        },
        {
          title: '是否主省',
          slot: 'mainCity',
          align: 'center',
          minWidth: 150
        }
      ],
      submitUuid: '', // 提交所需uuid（前端生成）
    };
  },
  watch: {
    /* 监听是否显示模态框的父组件传值 */
    visible (newValue) {
      this.dialogPriceSetVisible = newValue;
    }
  },
  methods: {
    /* 请求价格组数据方法 */
    async priceGroupRadioAction () {
      let params = {
        url: this.apiRequestUrl,
        type: 'post',
        data: {
          productUuids: this.productUuid,
          areaType: 1
        }
      };
      let { url, type, data } = params;
      if (!this.productUuid) {
        this.$Message.warning('没有productUuid,请确认');
        return;
      }
      this.tableLoading = true;
      let res = await ApiRequest(url, type, data, false);
      this.tableLoading = false;
      if (res.retStatus === '1') {
        res.retData.forEach((item) => {
          item.oldMainCityName = item.cityName;
          item.oldMainCityCode = item.cityCode;
          // item.mainCity = '2'
        });
        // 保存组别默认值
        this.provinceSetList = res.retData.map((item) => ({
          ...item,
          groupNumBy: item.groupNum
        }));
        this.priceGroupList = res.retData.reduce((value, item) => {
          if (item.canSetMain === '1') {
            value.push({
              groupNum: item.cityCode,
              groupName: item.cityName
            });
          }
          return value;
        }, []);
      }
    },
    /* 点击确定回调方法 */
    async submitAction () {
      let data = this.provinceSetList;
      data.forEach((value) => {
        value.productUuid = this.productUuid.join(',');
      });
      this.actionLoading = true;
      this.submitLoading = true;
      this.submitUuid = generateUuid(); // 每次二级弹框提交时重新生成
      let res = await ApiRequest(`${this.submitUrl}?uuid=${this.submitUuid}`, 'post', data, false);
      this.submitLoading = false;
      if (res.retStatus === '1') {
        this.parentGetTemplateFn(this.submitUuid);
        this.handleCancle();
      }
      this.actionLoading = false;
    },
    /* 关闭模态框的方法 */
    handleCancle () {
      this.dialogPriceSetVisible = false;
      this.$emit('update:visible', false);
    },
    /* 设置组输入框输入方法 */
    handleInputPriceGroup (data) {
      let { row, index } = data;
      this.provinceSetList[index] = row;
    },
    /* 选择是否是主城市 */
    handleChangeIsMainCity (data) {
      let { event, row, index } = data;
      this.provinceSetList[index].mainCity = event; // 单选赋值
      /* 同一 设置组 只能选一个主城市 */
      if (event === '2') {
        return;
      }
      this.provinceSetList.forEach((value, i) => {
        if (value.groupNum === row.groupNum) {
          value.groupName = row.oldMainCityName;
          if (i !== index) {
            this.provinceSetList[i].mainCity = '2';
          }
        }
      });
    },
    // 批量设置
    handleBatchSetting () {
      let { select } = this.formInline;
      if (select === '') {
        this.$Message.warning('请您先选中组别哦！');
        return;
      }
      // 获取选中的组别
      let val = this.provinceSetList.find((item) => item.cityCode === select);
      let { oldMainCityName, groupNumBy } = val;
      this.provinceSetList.forEach((item) => {
        // 判断是否选中了表格中相同的组别
        if (item.cityCode === select) {
          // 把选中组别置为主省
          item.mainCity = '1';
          // 从新赋值为初始值
          item.groupNum = item.groupNumBy;
          item.groupName = item.oldMainCityName;
        } else {
          item.groupNum = groupNumBy;
          item.groupName = oldMainCityName;
          // 如果之前设置过主省在从新赋值
          item.mainCity = item.mainCity === '1' ? '2' : item.mainCity;
        }
      });
    },
    // 各省成组
    handleToGroupByProvince () {
      this.provinceSetList = _.cloneDeep(this.provinceSetList).reduce((value, item, index) => {
        if (item.canSetMain === '1') {
          item.mainCity = '1';
          item.groupNum = (index + 1).toString();
        }
        value.push(item);
        return value;
      }, []);
      this.provinceSetList.filter(
        item => item.mainCity === '1' && item.canSetMain === '1'
      ).forEach((item, index) => {
        this.handleChangeIsMainCity({ event: item.mainCity, row: item, index });
      });
    }
  }
};
</script>
<style lang="less" scoped>
.heigher_table_wrap {
  margin-bottom: 15px;
}
</style>
